package com.kaibes.platform.member.db;

import java.util.List;

import org.springframework.stereotype.Service;

import com.kaibes.orm.curd.OrderType;
import com.kaibes.orm.curd.QueryBuilder;
import com.kaibes.orm.curd.SelectBuilder;
import com.kaibes.web.api.ResponseServiceImpl;

@Service
public class MemberLevelService extends ResponseServiceImpl<MemberLevel> {
    
    public boolean removeByLevel(int level) {
        return remove(QueryBuilder.newBuilder().eq("level", level).build()) > 0;
    }
    
    public MemberLevel getByExperience(long experience) {
        return getMapper().selectFirst(SelectBuilder.newBuilder()
                .addQuery(QueryBuilder.newBuilder().lt("experience", experience+1).build())
                .addOrder("experience", OrderType.DESC)
                .setSize(1)
                .build());
    }
    
    public MemberLevel getByLevel(int level) {
        return get(QueryBuilder.newBuilder().eq("level", level).build());
    }
    
    public List<MemberLevel> listAllLevelAndName() {
        return list("level", "name");
    }
    
    public List<MemberLevel> listLevelAndNamesByExperience(long experience) {
        return list(QueryBuilder.newBuilder().lt("experience", experience+1).build(), "level", "name");
    }
    
    public int getLevelByExperience(long experience) {
        MemberLevel memberLevel = getMapper().selectFirst(SelectBuilder.newBuilder()
                .addQuery(QueryBuilder.newBuilder().lt("experience", experience+1).build())
                .addColumn("level")
                .addOrder("experience", OrderType.DESC)
                .setSize(1)
                .build());
        if (memberLevel == null) {
            return 0;
        }
        return memberLevel.getLevel();
    }
    
    public MemberLevel getIdAndLevelAndNameByExperience(long experience) {
        return getMapper().selectFirst(SelectBuilder.newBuilder()
                .addQuery(QueryBuilder.newBuilder().lt("experience", experience+1).build())
                .addColumn("id")
                .addColumn("level")
                .addColumn("name")
                .addOrder("experience", OrderType.DESC)
                .setSize(1)
                .build());
    }
    
}
